package com.link.play.fit.ai.pushWorker

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.link.play.fit.ai.GlobalConfig.NO_VIP_NOTIFICATION_NAME
import com.link.play.fit.ai.R
import com.link.play.fit.ai.kv.AuthCache.pushCount
import com.link.play.fit.ai.ui.SplashAc
import com.link.play.fit.ai.utils.AppX
import com.link.play.fit.ai.utils.NotifycationUtils.intervals
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class PushNotificationWorker(
    context: Context,
    params: WorkerParameters
) : Worker(context, params) {
    // 存储字符串列表
    private var notifyList: MutableList<String> = mutableListOf()
    init {
        // 从资源文件中加载字符串数组
         val list:MutableList<String> = mutableListOf(context.getString(R.string.fast_track_your_dream_body_as_easily_as_taking_a_picture),
            context.getString(R.string.on_that_cut_or_bulk_let_us_make_your_life_easier),
            context.getString(R.string.all_it_takes_is_a_few_pictures_a_day_to_achieve_your_dream_body),
            context.getString(R.string.time_is_money_let_us_make_you_richer_by_speeding_up_food_logging),
            context.getString(R.string._1374_others_joined_today_don_t_procrastinate_getting_your_dream_body),
            context.getString(R.string.tired_of_manually_logging_your_food_it_takes_one_click_with_us),
            context.getString(R.string.still_not_convinced_chelsea_lost_15_lbs_in_two_months))
        notifyList = list.toMutableList()
    }
    override fun doWork(): Result {
        // 获取当前推送次数
        val currentIndex = pushCount
        // 发送推送通知
        sendNotification(applicationContext,currentIndex)
        // 更新推送次数并调度下一次
        if (currentIndex <= intervals.lastIndex) {
            scheduleNextPush(currentIndex + 1)
        }

        return Result.success()
    }
    private fun scheduleNextPush(nextCount:Int) {
        pushCount = nextCount
        // 计算延迟时间（转换为毫秒）
        val delayHours = intervals[nextCount]
        val delayMillis = delayHours * 60 * 60 * 1000L

        val workRequest = OneTimeWorkRequestBuilder<PushNotificationWorker>()
            .setInitialDelay(delayMillis, TimeUnit.MILLISECONDS)
            .build()
        WorkManager.getInstance(AppX.applicationContext)
            .enqueueUniqueWork(
                NO_VIP_NOTIFICATION_NAME,
                ExistingWorkPolicy.REPLACE,
                workRequest
            )
    }
    private fun sendNotification(context: Context,sequence: Int) {
        val channelId = "kcal_vip_channel_id"
        val channelName = "kcal_vip_channel_name"

        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(true)
            notificationManager.createNotificationChannel(channel)
        }
        val intent = Intent(applicationContext, SplashAc::class.java)
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(context, channelId)
//            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("Kcal AI")
            .setContentText(notifyList[sequence])
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setSmallIcon(R.mipmap.ic_notification)
            .setColor(applicationContext.getColor(R.color.color_17D995))
            .build()

        context.getSystemService(NotificationManager::class.java)
            .notify(Random.nextInt(), notification)
    }

}
